package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.conmon.MyPageData;
import com.woniuxy.mapper.*;
import com.woniuxy.pojo.*;
import com.woniuxy.pojo.dto.DoctorScheduleDTO;
import com.woniuxy.pojo.dto.SearchMedicalDTO;
import com.woniuxy.pojo.vo.AppointmentVO;
import com.woniuxy.pojo.vo.DoctorScheduleVO;
import com.woniuxy.service.DoctorScheduleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author admin
 * @description 针对表【doctor_schedule(医生/医院排班表)】的数据库操作Service实现
 * @createDate 2025-06-06 15:38:56
 */
@Service
public class DoctorScheduleServiceImpl extends ServiceImpl<DoctorScheduleMapper, DoctorSchedule>
        implements DoctorScheduleService {

    @Autowired
    private DoctorScheduleMapper doctorScheduleMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private MedicalPackageMapper medicalPackageMapper;
    @Autowired
    private HospitalMapper hospitalMapper;


    @Override
    public MyPageData getRegistrationData(int PageNum, int PageSize) {
        Page<DoctorSchedule> page = new Page<>(PageNum, PageSize);
        QueryWrapper<DoctorSchedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","doctor_id", "department_id", "schedule_date", "time_period", "start_time", "max_patients", "registered_count");
        Page<DoctorSchedule> doctorSchedulePage = doctorScheduleMapper.selectPage(page, queryWrapper);
        List<DoctorSchedule> doctorSchedules = doctorSchedulePage.getRecords();
        // 处理科室信息（构建"一级科室>二级科室"格式）
        doctorSchedules.forEach(item -> {
            if (item.getDepartmentId() != null) {
                Department department = departmentMapper.selectById(item.getDepartmentId());
                if (department != null) {
                    // 获取父科室名称
                    if (department.getParentId() != null && department.getParentId() > 0) {
                        Department parentDept = departmentMapper.selectById(department.getParentId());
                        item.setDepartmentName(parentDept.getName() + ">" + department.getName());
                    } else {
                        item.setDepartmentName(department.getName());
                    }
                }
            }
        });
        //处理医生名字信息
        doctorSchedules.forEach(item -> {
            Doctor doctor = doctorMapper.selectById(item.getDoctorId());
            if (doctor != null) {
                item.setDoctorName(doctor.getName());
            }
        });
        return new MyPageData(doctorSchedulePage.getTotal(), doctorSchedules);
    }

    @Override
    public Page<DoctorScheduleVO> searchQuery(DoctorScheduleDTO queryDTO, Integer pageNum, Integer pageSize) {
        // 1. 构建分页对象
        Page<DoctorSchedule> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        QueryWrapper<DoctorSchedule> queryWrapper = new QueryWrapper<>();

        // 添加条件过滤
        if (queryDTO.getDoctorId() != null) {
            queryWrapper.eq("doctor_id", queryDTO.getDoctorId());
        }

        if (queryDTO.getDepartmentId() != null) {
            queryWrapper.eq("department_id", queryDTO.getDepartmentId());
        }

        if (queryDTO.getMaxPatients() != null) {
            queryWrapper.eq("max_patients", queryDTO.getMaxPatients());
        }
        // 3. 执行分页查询
        Page<DoctorSchedule> schedulePage = baseMapper.selectPage(page, queryWrapper);

        // 4. 创建VO分页对象
        Page<DoctorScheduleVO> voPage = new Page<>();
        BeanUtils.copyProperties(schedulePage, voPage, "records");

        // 5. 转换records
        List<DoctorScheduleVO> voList = schedulePage.getRecords().stream().map(schedule -> {
            DoctorScheduleVO vo = new DoctorScheduleVO();
            BeanUtils.copyProperties(schedule, vo);

            // 关联查询医生和科室信息
            Doctor doctor = doctorMapper.selectById(schedule.getDoctorId());
            Department department = departmentMapper.selectById(schedule.getDepartmentId());

            vo.setDoctorName(doctor != null ? doctor.getName() : "");
            vo.setDepartmentName(department != null ? department.getName() : "");

            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public AppointmentVO getAppointmentDetail(Integer id) {
        // 1. 获取排班记录
        DoctorSchedule schedule = doctorScheduleMapper.selectById(id);
        if (schedule == null) {
            throw new RuntimeException("未找到ID为" + id + "的排班记录");
        }

        // 2. 获取医生信息
        Doctor doctor = doctorMapper.selectById(schedule.getDoctorId());

        // 3. 构建返回对象
        AppointmentVO vo = new AppointmentVO();

        // 设置医生姓名（完全匹配图片中的"张三"）
        vo.setDoctorName(doctor != null ? doctor.getName() : "未知医生");
        vo.setId(schedule.getId());
        vo.setScheduleDate(schedule.getScheduleDate());
        vo.setTimePeriod(schedule.getTimePeriod());
        vo.setRegisteredCount(schedule.getRegisteredCount());
        return vo;
    }

    @Override
    public MyPageData getDoctorDetail(int PageNum, int PageSize) {
        Page<DoctorSchedule> page = new Page<>(PageNum, PageSize);
        QueryWrapper<DoctorSchedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","doctor_id", "department_id", "start_time","fee");
        Page<DoctorSchedule> doctorSchedulePage = doctorScheduleMapper.selectPage(page, queryWrapper);
        List<DoctorSchedule> doctorSchedules = doctorSchedulePage.getRecords();
        // 处理科室信息（构建"一级科室>二级科室"格式）
        doctorSchedules.forEach(item -> {
            if (item.getDepartmentId() != null) {
                Department department = departmentMapper.selectById(item.getDepartmentId());
                if (department != null) {
                    // 获取父科室名称
                    if (department.getParentId() != null && department.getParentId() > 0) {
                        Department parentDept = departmentMapper.selectById(department.getParentId());
                        item.setDepartmentName(parentDept.getName() + ">" + department.getName());
                    } else {
                        item.setDepartmentName(department.getName());
                    }
                }
            }
        });
        //处理医生名字信息
        doctorSchedules.forEach(item -> {
            Doctor doctor = doctorMapper.selectById(item.getDoctorId());
            if (doctor != null) {
                item.setDoctorName(doctor.getName());
            }
        });
        return new MyPageData(doctorSchedulePage.getTotal(), doctorSchedules);
    }

    @Override
    public MyPageData getMedicalData(Integer pageNum, int pageSize) {
        Page<DoctorSchedule> page = new Page<>(pageNum, pageSize);
        QueryWrapper<DoctorSchedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","hospital_id", "package_id", "start_time", "schedule_date", "time_period", "max_patients", "registered_count");
        Page<DoctorSchedule> doctorSchedulePage = doctorScheduleMapper.selectPage(page, queryWrapper);
        List<DoctorSchedule> doctorSchedules = doctorSchedulePage.getRecords();
        //  处理医院信息
        doctorSchedules.forEach(item -> {
            if (item.getHospitalId() != null) {
                Hospital hospital = hospitalMapper.selectById(item.getHospitalId());
                if (hospital != null) {
                    item.setHospitalName(hospital.getName());
                }

            }
        });
        // 处理套餐信息
        doctorSchedules.forEach(item -> {
            if (item.getPackageId() != null) {
                MedicalPackage medicalPackage = medicalPackageMapper.selectById(item.getPackageId());
                if (medicalPackage != null) {
                    item.setPackageName(medicalPackage.getPackageName());
                }
            }
        });
        return new MyPageData(doctorSchedulePage.getTotal(), doctorSchedules);
    }

    @Override
    public Page<DoctorScheduleVO> searchDoctorSchedule(SearchMedicalDTO query, Integer pageNum, Integer pageSize) {
        // 1. 创建分页对象
        Page<DoctorSchedule> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        QueryWrapper<DoctorSchedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(
                "id", "hospital_id", "package_id", "start_time",
                "schedule_date", "time_period", "max_patients", "registered_count"
        );

        // 3. 添加动态查询条件（修正参数绑定方式）
        if (StringUtils.isNotBlank(query.getHospitalName())) {
            queryWrapper.inSql("hospital_id",
                    String.format("SELECT id FROM hospital WHERE name LIKE '%%%s%%'", query.getHospitalName()));
        }

        if (StringUtils.isNotBlank(query.getPackageName())) {
            queryWrapper.inSql("package_id",
                    String.format("SELECT id FROM medical_package WHERE package_name LIKE '%%%s%%'", query.getPackageName()));
        }

        if (query.getMaxPatients() != null) {
            queryWrapper.le("max_patients", query.getMaxPatients());
        }

        // 4. 执行分页查询
        Page<DoctorSchedule> doctorSchedulePage = doctorScheduleMapper.selectPage(page, queryWrapper);

        // 5. 转换为VO对象并填充关联数据
        List<DoctorScheduleVO> voList = doctorSchedulePage.getRecords().stream().map(schedule -> {
            DoctorScheduleVO vo = new DoctorScheduleVO();
            BeanUtils.copyProperties(schedule, vo);

            // 填充医院信息
            if (schedule.getHospitalId() != null) {
                Hospital hospital = hospitalMapper.selectById(schedule.getHospitalId());
                if (hospital != null) {
                    vo.setHospitalName(hospital.getName());
                }
            }

            // 填充套餐信息
            if (schedule.getPackageId() != null) {
                MedicalPackage medicalPackage = medicalPackageMapper.selectById(schedule.getPackageId());
                if (medicalPackage != null) {
                    vo.setPackageName(medicalPackage.getPackageName());
                }
            }

            return vo;
        }).collect(Collectors.toList());

        // 6. 构建返回结果
        Page<DoctorScheduleVO> resultPage = new Page<>();
        BeanUtils.copyProperties(doctorSchedulePage, resultPage);
        resultPage.setRecords(voList);

        return resultPage;
    }
}




